package me.yiyou.meihua.net

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitClient {
    private const val BASE_URL = "https://spark-api-open.xf-yun.com/v2/"
    private const val TIMEOUT = 300L  // 秒  非流式的比较耗时,所以设置长一点
    private val xinghuoApi = AppConfig.getString("XingHuoAPI") // TODO: 替换为你自己的token

    private val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    // OkHttp 配置,直接移除超时时间
    private val okHttpClient: OkHttpClient by lazy {
        OkHttpClient.Builder().apply {
            connectTimeout(0, TimeUnit.SECONDS)
            readTimeout(0, TimeUnit.SECONDS)
            writeTimeout(0, TimeUnit.SECONDS)

            // 根据实际需求添加公共请求头
            addInterceptor { chain ->
                val request = chain.request().newBuilder()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .addHeader("Authorization", "Bearer " + xinghuoApi)
                    .build()
                chain.proceed(request)
            }
            addInterceptor(LoggingInterceptor())
        }.build()
    }

    // 创建API服务
    fun <T> createService(service: Class<T>): T {
        return retrofit.create(service)
    }
}